package org.jeecg.modules.openai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.openai.entity.AiImgCreateRecord;
import org.jeecg.modules.openai.entity.AiImgPaymentRecord;
import org.jeecg.modules.openai.mapper.AiImgPaymentRecordMapper;
import org.jeecg.modules.openai.service.IAiImgCreateRecordService;
import org.jeecg.modules.openai.service.IAiImgPaymentRecordService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: ai_img_payment_record
 * @Author: jeecg-boot
 * @Date:   2023-02-23
 * @Version: V1.0
 */
@Service
public class AiImgPaymentRecordServiceImpl extends ServiceImpl<AiImgPaymentRecordMapper, AiImgPaymentRecord> implements IAiImgPaymentRecordService {

    @Autowired
    private IAiImgCreateRecordService createRecordService;
    @Autowired
    private ISysUserService userService;

    @Override
    public AiImgCreateRecord pay(String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        AiImgPaymentRecord paymentRecord = this.getOne(new QueryWrapper<AiImgPaymentRecord>()
                .eq("user_id",sysUser.getId()).eq("record_id",id));
        AiImgCreateRecord createRecord = createRecordService.getById(id);
        if(paymentRecord!=null){
            throw new JeecgBootException("已经支付过了！");
        }else{
            SysUser user = userService.getById(sysUser.getId());
            //扣除购买者积分
            userService.updateUserScore(user.getId(),-1*createRecord.getScore());

            //增加发布者积分
            userService.updateUserScore(createRecord.getUserId(),createRecord.getScore());

            paymentRecord = new AiImgPaymentRecord();
            paymentRecord.setRecordId(createRecord.getId());
            paymentRecord.setPrice(createRecord.getScore());
            paymentRecord.setUserId(user.getId());
            save(paymentRecord);

            return createRecord;
        }
    }
}
